package com.lg.meng.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import butterknife.ButterKnife;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lg.meng.Lifecycer;
import com.lg.meng.MessageEvent;
import com.lg.meng.ReceiverRegistor;
import com.lg.meng.dialog.LoadingDialog;
import com.lg.meng.dialog.PermissionsSetDialog;
import com.lg.meng.receiver.NetBroadcastReceiver;
import com.lg.meng.utils.LifecyclerInjectHelper;
import com.lg.meng.utils.MvpInjectHelper;
import com.lg.meng.utils.NetBroadcastHelper;
import com.lg.meng.utils.PermissionsUtils;
import com.lg.meng.utils.ReceiverInjectHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


public abstract class BaseMvpActivity extends AppCompatActivity implements NetBroadcastReceiver.OnNetworkChangeListener {
    public List<BaseMvpPresenter> presenterList = new ArrayList<>();
    private NetBroadcastHelper netBroadcastHelper;
    private ReceiverRegistor receiverRegistor;
    private Lifecycer lifecyer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        beforeSetContentView();
        setContentView();
        MvpInjectHelper.inject(this);
        ButterKnife.bind(this);
        afterSetContentView();
        EventBus.getDefault().register(this);
        netBroadcastHelper = new NetBroadcastHelper(this);
        receiverRegistor = ReceiverInjectHelper.inject(this);
        lifecyer = LifecyclerInjectHelper.inject(this);
    }

    /**
     * 设置布局(布局id或view对象)
     */
    protected void setContentView() {
        int layoutId = provideContentViewId();
        if (layoutId != 0) {
            setContentView(layoutId);
        } else {
            View view = provideContentView();
            if (view != null) {
                setContentView(view);
            } else {
                throw new RuntimeException("please provide a layout id or view!!");
            }
        }
    }

    protected abstract int provideContentViewId();

    protected abstract void beforeSetContentView();

    protected abstract void afterSetContentView();

    protected View provideContentView() {
        return null;
    }

    boolean isExeDestory; //是否执行了exeDestory

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!isExeDestory) {
            exeDestory();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        netBroadcastHelper.registNetBroadcastReceiver(this);
    }

    protected void exeDestory() {
        isExeDestory = true;
        for (BaseMvpPresenter presenter : presenterList) {
            if (presenter != null) {
                presenter.detachView();
            }
        }
        if (!isUnregisterEventBusOnPause()) {
            EventBus.getDefault().unregister(this);
        }

        if (lifecyer != null) {
            lifecyer.onDestory();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        netBroadcastHelper.unregistNetBroadcastReceiver(this);
        if (isUnregisterEventBusOnPause()) {
            EventBus.getDefault().unregister(this);
        }
        if (isFinishing()) {
            exeDestory();
        }
    }

    protected boolean isUnregisterEventBusOnPause() {
        return false;
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onNetworkChange() {
        if (!NetworkUtils.isAvailableByPing()) {
            ToastUtils.showLong("网络异常,请检查网络");
        }
    }

    @Override
    public void onWifiStateDisabling() {

    }

    @Override
    public void onWifiStateDisabled() {

    }

    @Override
    public void onWifiStateEnabling() {

    }

    @Override
    public void onWifiStateEnabled() {

    }

    @Override
    public void onWifiStateUnknown() {

    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                InputMethodManager imm =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS
                );
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // Return whether touch the view.
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent) {

    }

    protected void registReceiver() {
        if (receiverRegistor != null) {
            receiverRegistor.registReceiver();
        }
    }

    protected void unRegistReceiver() {
        if (receiverRegistor != null) {
            receiverRegistor.unregistReceiver();
        }
    }

    private LoadingDialog loadingDialog;

    public void showLoadingDialog(boolean cancelable, String tips) {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        }
        if (!TextUtils.isEmpty(tips)) {
            loadingDialog.loadingTips(tips);
        }
        loadingDialog.setCancelable(cancelable);
        loadingDialog.setCanceledOnTouchOutside(cancelable);
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    public void showLoadingDialog() {
        showLoadingDialog(true, null);
    }

    public void showLoadingDialog(boolean cancelable) {
        showLoadingDialog(cancelable, null);
    }

    public void dissmissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    private static final int NONE_REQUEST_CODE = -10000;

    public void jumpTo(Class clz) {
        jumpToCommon(clz, NONE_REQUEST_CODE);
    }

    public void jumpTo(Class clz, Serializable... serializables) {
        jumpToCommon(clz, NONE_REQUEST_CODE, serializables);
    }

    public void jumpToCommon(Class clz, int requestCode, Serializable... serializables) {
        Intent intent = new Intent(this, clz);
        if (serializables != null && serializables.length > 0) {
            Bundle bundle = new Bundle();
            for (int i = 0; i < serializables.length; i++) {
                Serializable serializable = serializables[i];
                bundle.putSerializable(i + "", serializable);
            }
            intent.putExtras(bundle);
        }
        if (requestCode == NONE_REQUEST_CODE) {
            startActivity(intent);
        } else {
            startActivityForResult(intent, requestCode);
        }
    }

    public Serializable getParam(int index) {
        return getParam(index, getIntent());
    }

    public Serializable getParam(int index, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (bundle == null) {
            return null;
        }
        Serializable param = bundle.getSerializable(index + "");
        return param;
    }

    private PermissionsSetDialog permissionsSetDialog;

    public void showPermissionsSetDialog(String permissions) {
        if (permissionsSetDialog == null) {
            permissionsSetDialog = new PermissionsSetDialog(this);
        }
        permissionsSetDialog.show(permissions);
    }

    public void dismissPermissionsSetDialog() {
        if (permissionsSetDialog != null) {
            permissionsSetDialog.dismiss();
        }
    }

    public void permissionRun(Runnable runnable, String permissionTips, String... permissions) {
        PermissionsUtils.permissionRun(this, runnable, permissionTips, permissions);
    }
}
